import numpy as np
import pandas as pd
import datetime as dt
import requests
import json
import pandas as pd

class LocalAPITrader:
    def __init__(self):
        self.api_url = "http://{你的公网ip地址}:5000/receive_signal"

    def send_order(self, data):
        try:
            headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'JoinQuant-Trader'
            }
            # 确保发送的是JSON格式数据
            response = requests.post(
                self.api_url,
                json=data,  # 自动转换为JSON
                headers=headers,
                timeout=5  # 超时设置
            )
            response.raise_for_status()  # 检查HTTP错误
            print("推送成功:", response.json())
            return response.json()
        except requests.exceptions.RequestException as e:
            print("推送失败 - 网络错误:", str(e))
        except Exception as e:
            print("推送失败 - 其他错误:", str(e))
    
api_trader = LocalAPITrader()

def send_order(result):
    '''
    发送函数
    status: 状态, 一个OrderStatus值
    add_time: 订单添加时间, [datetime.datetime]对象
    is_buy: bool值, 买还是卖，对于期货:
    开多/平空 -> 买
    开空/平多 -> 卖
    amount: 下单数量, 不管是买还是卖, 都是正数
    filled: 已经成交的股票数量, 正数
    security: 股票代码
    order_id: 订单ID
    price: 平均成交价格, 已经成交的股票的平均成交价格(一个订单可能分多次成交)
    avg_cost: 卖出时表示下卖单前的此股票的持仓成本, 用来计算此次卖出的收益. 买入时表示此次买入的均价(等同于price).
    side: 多/空，'long'/'short'
    action: 开/平， 'open'/'close'
    commission交易费用（佣金、税费等）
    '''
    data={}
    data['状态']=str(result.status)
    data['订单添加时间']=str(result.add_time)
    data['买卖']=str(result.is_buy)
    data['下单数量']=str(result.amount)
    data['已经成交']=str(result.filled)
    data['股票代码']=str(result.security)
    data['订单ID']=str(result.order_id)
    data['平均成交价格']=str(result.price)
    data['持仓成本']=str(result.avg_cost)
    data['多空']=str(result.side)
    data['交易费用']=str(result.commission)
    result=str(data)
    api_trader.send_order(data)
    return data

def dm_order(func):
    '''
    继承order对象 数据交易函数
    '''
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result == None:
            return
        send_order(result)
        return result
    return wrapper

def dm_order_target(func):
    '''
    继承order_target对象 百分比
    '''
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result == None:
            return        
        send_order(result)
        return result
    return wrapper

def dm_order_value(func):
    '''
    继承order_value对象 数量
    '''
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result == None:
            return        
        send_order(result)
        return result
    return wrapper

def dm_order_target_value(func):
    '''
    继承order_target_value对象 数量
    '''
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if result == None:
            return        
        send_order(result)
        return result
    return wrapper

order = dm_order(order)
order_target = dm_order_target(order_target)
order_value = dm_order_value(order_value)
order_target_value = dm_order_target_value(order_target_value)